var tree;
function makeSubmit(){
	var result=[];
	var data=tree.getCheckedNodes(true);
	for(var i=0;i<data.length;i++){
		if(data[i].nodeType==1){
			var t={};
			t["nodeType"]=1;
			t["id"]=data[i].id;
			t["hostId"]=data[i].hostId;
			result.push(t);
		}else if(data[i].nodeType==2){
			var t={};
			t["nodeType"]=2;
			t["id"]=data[i].id;
			t["hostId"]=data[i].hostId;
			t["moduleId"]=data[i].moduleId;
			result.push(t);
		}
	}
	$.ajax({
		type: 'POST',
        url: "system/role!saveForConfigPermission.action",
        data: {
        	'systemRole.id':$('#roleId').val(),
        	'postData':JSON.stringify(result)
        },
        success: function(data){
        	if(data.ok){
        		showMessage('角色配置完成',function(){
        			closeDialog();
        		});
	    	}else{
	    		showMessage('角色配置失败：'+data.message,null,'error');
	    	}
        }
	});
	
	
	
}

function changeCheckState(node,state){
	if(node.children&&node.children.length>0){
		for(var i=0;i<node.children.length;i++){
			changeCheckState(node.children[i],state);
		}
	}
	tree.checkNode(node,state,true);
}
 
function selectAll(){
	tree.checkAllNodes(true);
}
 
function clearSelect(){
	tree.checkAllNodes(false);
}

function doDataConvert(obj){
    for(var i=0;i<obj.length;i++){
        var name=obj[i].name;
        var icon=obj[i].icon?obj[i].icon:'fa fa-circle-o';
        obj[i].name='<span class="'+icon+'" />&nbsp;'+name;//+'<button class="btn btn-link btn-xs"></button>';
        if(obj[i].children&&obj[i].children.length>0){
            doDataConvert(obj[i].children);
        }
    }
    return obj;
}

$(function(){
	var temp=$("<div><img src='res/image/system/ajaxload.gif' alt='' /></div>");
	$("#form").append(temp);
	var roleId=$("#roleId").val();

	$.ajax({
		url: 'system/role!queryPermissionForConfig.action?systemRole.id='+roleId+'&__t='+$.mothin.util.getStamp(),
		type: 'GET',
		dataType: 'json',
		error: function(){
			temp.remove();
			$("#panel").html("网络错误，请重试");
		},
		success: function(d){
			if(d&&d.ok){
				var data=doDataConvert(d.value);
				temp.remove();
				var setting = {
					check: {
						enable: true,
						chkboxType:{"Y":"p", "N":"ps"}
					},
					callback: {
						onRightClick: function(event, treeId, treeNode) {
							changeCheckState(treeNode,!treeNode.checked);
						}
					},
					view: {
				        showIcon: false,
				        nameIsHTML: true,
				        showTitle:false
				    }
				};
				tree=$.fn.zTree.init($("#tree"), setting,data);
				var nodes = tree.getCheckedNodes(true);
				for (var i=0, l=nodes.length; i < l; i++) {
					if(nodes[i].isParent){
						continue;
					}
					tree.checkNode(nodes[i], nodes[i].checked, true);
				}
			}
		}
	});
});